package com.itheima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;


@Service
@AllArgsConstructor
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper,Clazz> implements ClazzService {

    private ClazzMapper clazzMapper;
    private EmpMapper empMapper;
    @Override
    public PageResult<Clazz> queryPage(String name, LocalDate begin, LocalDate end, int page, int pageSize) {

        Page<Clazz> pageInfo = Page.of(page, pageSize);
//        LambdaQueryWrapper<Clazz> queryWrapper = new LambdaQueryWrapper<>();

        Page<Clazz> result = lambdaQuery().like(StringUtils.hasLength(name), Clazz::getName, name)
                .between(begin != null && end != null, Clazz::getBeginDate, begin, end)
                .page(pageInfo);

        List<Clazz> clazzes = result.getRecords();
        List<Integer> collect = clazzes.stream().map(Clazz::getMasterId
        ).toList();
        List<Emp> empList = empMapper.selectBatchIds(collect);
        clazzes.forEach(clazz -> {
            empList.stream().filter(emp -> emp.getId().equals(clazz.getMasterId()))
                    .findFirst().ifPresent(emp -> clazz.setMasterName(emp.getName()));
        });

        return new PageResult<>(result.getTotal(), clazzes);
    }

    @Override
    public void saveClazz(Clazz clazz) {

    }
}
